import sys
sys.path.append('../face_recog/insightface/deploy')
sys.path.append('../face_recog/insightface/src/common')
# import face_preprocess
from face_recog.insightface.src.common import face_preprocess
from imutils import paths
import numpy as np
# import face_model
from face_recog.insightface.deploy import face_model
import argparse
import pickle
import cv2
import os
# from face_embedding.utils import argsutils
# from face_embedding.pkl_demo import make_pkl
# args = argsutils.Facemodel().args
# from pathlib import Path
#
#
#
# class write_pkl():
#     def __init__(self,args):
#         self.args = args
#         if not Path(self.args.all).exists():
#             make_pkl(self.args.all)
#             self.data_all = {}
#             self.data_all['user_id'] = []
#             self.data_all['embeddings'] = []
#         if os.path.getsize(self.args.all)> 0:
#             self.data_all = pickle.load(open(self.args.all, 'rb'))
#         else:
#             self.data_all = {}
#             self.data_all['user_id'] = []
#             self.data_all['embeddings'] = []
#     def partment_add(self,dic,partment):
#         self.part_dir = self.args.partment + '_' + partment + '.pkl'
#         if not Path(self.part_dir).exists():
#             make_pkl(self.part_dir)
#         if os.path.getsize(self.part_dir) > 0:
#             self.data_part = pickle.load(open(self.part_dir, 'rb'))
#         else:
#             self.data_part = {}
#             self.data_part['user_id'] = []
#             self.data_part['embeddings'] = []
#         # print(self.data_part)
#         # print(type(self.data_part))
#         self.data_part['user_id'].append(dic['user_id'])
#         self.data_part['embeddings'].append(dic['embeddings'])
#         print('目前部门%s总共有id=%d，embeddings=%d'%(partment,len(self.data_part['user_id']),len(self.data_part['embeddings'])))
#         f = open(self.part_dir, 'wb')
#         f.write(pickle.dumps(self.data_part))
#         f.close()
#     def all_add(self,dic):
#
#         self.data_all['user_id'].append(dic['user_id'])
#         self.data_all['embeddings'].append(dic['embeddings'])
#         print('目前总共有id=%d,embeddings=%d'%(len(self.data_all['user_id']),len(self.data_all['embeddings'])))
#         f = open(self.args.all, 'wb')
#         f.write(pickle.dumps(self.data_all))
#         f.close()
#     def re_regeister(self,dic,user_id,partment):
#         # print(dic)
#         # print('dadadadadaaaaaa')
#         if user_id not in self.data_all['user_id']:
#             print('user_id%s not in all ids'%(user_id))
#         self.part_dir = self.args.partment + '_' + partment + '.pkl'
#         if not Path(self.part_dir).exists():
#             print('this partment isnot exists')
#         if os.path.getsize(self.part_dir) > 0:
#             self.data_part = pickle.load(open(self.part_dir, 'rb'))
#         else:print('this partment is empty')
#         if user_id not in self.data_part['user_id']:
#             print('user_id_%s not in this partment'%(user_id))
#         #all部分
#         i= 0
#         while user_id in self.data_all['user_id']:
#             i = i+1
#             print('%d张图片被移除'%(i))
#             ind = self.data_all['user_id'].index(user_id)
#             for key_ in self.data_all.keys():
#                 del self.data_all[key_][ind]
#
#         #partment部分
#         i=0
#         while user_id in self.data_part['user_id']:
#             i = i+1
#             print('%d张图片从该部门被移除' % (i))
#             ind = self.data_part['user_id'].index(user_id)
#             for key_ in self.data_part.keys():
#                 del self.data_part[key_][ind]
#
#         for i in range(len(dic['user_id'])):
#             dic_tem = {
#                 "names": dic['names'][i],
#                 "user_id": dic['user_id'][i],
#                 "embeddings": dic['embeddings'][i]
#             }
#             self.all_add(dic_tem)
#             self.data_part['user_id'].append(dic['user_id'][i])
#             self.data_part['embeddings'].append(dic['embeddings'][i])
#             print('目前部门%s总共有id=%d，embeddings=%d' % (
#             partment, len(self.data_part['user_id']), len(self.data_part['embeddings'])))
#         f = open(self.part_dir, 'wb')
#         f.write(pickle.dumps(self.data_part))
#         f.close()

# print("[INFO] quantifying faces...")
# file_dir = args.embeddings[0: args.embeddings.rindex('/')]
# print(file_dir)
# if not os.path.isdir(file_dir):
#     os.makedirs(file_dir)
# data = write_pkl(args)
# print(data.data_all)
# embedding_model = face_model.FaceModel(args)


def re_register_pkl(user_id,user_name,group_id,img_dirs, embedding_model):
    # if user_id not in data.data_all['user_id']:
    #     print('输入了错误的id')
    #     return (90011, '该用户未注册'), None

    # print(len(data['names']))
    total = 0
    user_name_lst = []
    user_id_lst = []
    face_embedding_lst = []
    for (i, imagePath) in enumerate(img_dirs):
        # extract the person name from the image path
        # print(img_dirs)
        print("[INFO] processing image {}/{}".format(i + 1, len(img_dirs)))
        # name = file_dir.split('/')[-1]
        # print(name)

        # load the image
        # image = cv2.imread(imagePath)
        image = imagePath

        # convert face to RGB color
        nimg = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        nimg = cv2.resize(nimg, (112, 112))
        nimg = np.transpose(nimg, (2, 0, 1))
        # Get the face embedding vector
        face_embedding = embedding_model.get_feature(nimg)
        # print(face_embedding.shape)
        user_name_lst.append(user_name)
        user_id_lst.append(user_id)
        face_embedding_lst.append(face_embedding)
    # dict_tem = {
    #     "names":user_name_lst,
    #     "user_id":user_id_lst,
    #     "embeddings":face_embedding_lst
    # }
    # data.re_regeister(dict_tem,user_id,group_id)

    return None, face_embedding_lst

def re_register_pkl_embedding(user_id,user_name,group_id, face_embeddings):
    user_name_lst = []
    user_id_lst = []
    face_embedding_lst = []
    for (i, face_embedding) in enumerate(face_embeddings):
        user_name_lst.append(user_name)
        user_id_lst.append(user_id)
        face_embedding_lst.append(face_embedding)

    return None, face_embedding_lst

def register_pkl_embedding(user_id,user_name,group_id, face_embeddings):
    embeddings = []
    for (i, face_embedding) in enumerate(face_embeddings):
        dict_tem = {
            "names":user_name,
            "user_id":user_id,
            "embeddings":face_embedding
        }
        embeddings.append(face_embedding)

    return None, embeddings

def register_pkl(user_id,user_name,group_id,img_dirs, embedding_model):
    if user_id == None:
        print('insert user id')
    if user_name == None:
        print('insert user_name')
    if group_id is None:
        print('insert group_id')

    # if user_id in data.data_all['user_id']:
    #     i = 0
    #     for ids in data.data_all['user_id']:
    #         if user_id == ids:
    #             i +=1
    #     if  i>2:
    #         return (90009, '该用户已注册'), None
    # print(len(data['names']))
    total = 0
    embeddings = []
    for (i, imagePath) in enumerate(img_dirs):
        # extract the person name from the image path
        # print(img_dirs)
        print("[INFO] processing image {}/{}".format(i + 1, len(img_dirs)))
        # name = file_dir.split('/')[-1]
        # print(name)

        # load the image
        image = imagePath

        # convert face to RGB color
        nimg = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        nimg = cv2.resize(nimg, (112, 112))
        nimg = np.transpose(nimg, (2, 0, 1))
        # Get the face embedding vector
        face_embedding = embedding_model.get_feature(nimg)
        print(face_embedding.shape)
        dict_tem = {
            "names":user_name,
            "user_id":user_id,
            "embeddings":face_embedding
        }
        # data.all_add(dic =dict_tem)
        # data.partment_add(dic =dict_tem,partment=group_id)
        embeddings.append(face_embedding)

    return None, embeddings
    # print(len(data['names']))
# register_pkl('chenyicheng','10002','../images/chenyicheng')


# def check_id(user_id):
#     print(data.data_all['user_id'])
#     if user_id in data.data_all['user_id']:
#         print('user_id%s exisist'%(user_id))
#         return True
#     return False